package managers.messengerManager;

import java.util.Calendar;
import java.util.Hashtable;

import managers.conversationManager.ConversationManager;
import managers.conversationManager.OfflineConversation;
import spotGUI.floatingChatGUI.FloatingChat;
import spotGUI.floatingChatGUI.FloatingChatFrame;
import utils.ManagingMessage;
import utils.StackTracePrinter;
import utils.UserData;
import utils.UserState;

public class ManageBroadcastPacketRunnable implements Runnable {


	private ManagingMessage managingMessage;
	
	public ManageBroadcastPacketRunnable (ManagingMessage managingMessage) {
		this.managingMessage = managingMessage;
		managePacket();
	}
	
	@Override
	public void run() {
		managePacket();
	}
	
	
	private void managePacket() {
		
		MessengerManager.getSharedInstance().setRecentFeedbackFromServer(true);
		
		switch (managingMessage.getType()) {
		case BROADCAST_MESSAGE:
			viewBroadcastMessage((String) managingMessage.getProperty("message"), (Integer) managingMessage.getProperty("senderId")); 
			break;

		case CURRENT_SITUATION:
			MessengerManager.getSharedInstance().getUsersManager().updateUsers((Hashtable<Integer, UserState>) managingMessage.getProperty("onlineUsers"), false);
			System.out.println("UPDATE FROM BROADCAST");
			break;
		}

	}
	
	private void viewBroadcastMessage (Object message, int senderId) {
		FloatingChat frame = ConversationManager.getSharedInstance().getChatManager().getChat(senderId);
		if (frame == null) {
			frame = new FloatingChatFrame();
			UserData user = MessengerManager.getSharedInstance().getDataManager().getUser(senderId);
			frame.setReceiverName(user.getProperty("firstName")+" "+user.getProperty("surname"));
			ConversationManager.getSharedInstance().getChatManager().addChat(senderId, frame);
			frame.setConversation(new OfflineConversation(senderId));
		}
		try {
			frame.updateConversation((String)message, true, Calendar.getInstance().getTime());
			frame.setVisible(true);
		} catch (Exception e) {
			//do nothing
			StackTracePrinter.print(e);
		}
	}
	
}
